package com.copa.gamestore.security.validation;

import com.copa.gamestore.module.user.domain.User;
import com.copa.gamestore.module.user.domain.dto.UserDto;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.validation.ValidationException;
import java.util.Objects;

/**
 * @author copa
 * @createDate 2022-09-23 11:45
 * @function
 */
@Aspect
@Component
public class AuthValidation {

    @Pointcut("@annotation(com.copa.gamestore.security.annotation.Auth)")
    public void authPointcut() {
    }

    //通过方法名获取切入点
    @Around("authPointcut()")
    public Object hasPermissions(ProceedingJoinPoint joinPoint) throws Throwable {
        //ObjectMapper objectMapper = new ObjectMapper();

        Object[] args = joinPoint.getArgs();
        //UserDto userDto = objectMapper.readValue(.toString(), UserDto.class);
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if ("anonymousUser".equals(principal)) {
            throw new ValidationException("请登录再操作~");
        }
        User loginUser = (User) principal;
        if (args[0] instanceof User) {
            User user = (User) args[0];
            if (!Objects.equals(loginUser.getId(), user.getId())) {
                throw new ValidationException("不是当前用户，不能操作~");
            }
            joinPoint.proceed();
            return joinPoint;
        }
        //userdto
        UserDto user = (UserDto) args[0];
        if (!Objects.equals(loginUser.getId(), user.getId())) {
            throw new ValidationException("不是当前用户，不能操作~");
        }
        joinPoint.proceed();
        return joinPoint;
    }


}
